package com.streetsmart;

/**
 * 
 * @author bhavani sudha
 *
 */
import android.database.sqlite.*;
import android.database.Cursor;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContentValues;
import android.content.Intent;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import org.json.JSONException;

/**
 * 
 * Handles the database. Contains five main tables EventsDB - which stores the
 * details of events MustEventsSchedule = which stores details on the specific
 * events. Used for notification of specific events ReturnLocation - which
 * records details on return locations for users. RecentLocations - which
 * contains recent user locations also used to track where he is
 * UserEnteredAddresses - which stores all the addresses entered by the user.
 * Mainly used for autocompletion in UI
 * 
 */
public class DBManager extends SQLiteOpenHelper {
	static final String dbName = "EventsDB";
	static final String tableName = "Events";
	static final String colId = "_id";
	static final String colName = "name";
	static final String colCategory = "category";
	static final String colLatitude = "latitude";
	static final String colLongitude = "longitude";
	static final String colAddress = "address";
	static final String colStartTime = "startTimeStamp";
	static final String colEndTime = "endTimeStamp";
	static final String colState = "state";
	static final String colType = "type";
	static final String mustEventsScheduleTable = "MustEventsSchedule";
	static final String colEventId = "event_id";
	static final String colEventStartTime = "startTimeStamp";
	static final String returnLocationTable = "ReturnLocation";
	static final String recentLocationPoints = "RecentLocations";
	static final String userEneteredrecentAddresses = "UserEnteredAddresses";
	static long firstRecentLocation;
	static long lastRecentLocation;
	final static int size = 10;

	Context context;
	SQLiteDatabase db;
	AlarmManager alarmMgr;
	Intent intent;
	PendingIntent pendingIntent;
	static int requestCode = 0;

	// TODO store as Date object. So that receier can direct compare instead of
	// conversions.
	// TODO handle repeated events later. May be need to add another fiel in the
	// table caleed Repeat.

	public DBManager(Context context) {
		super(context, dbName, null, 1);
		this.context = context;
		alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		intent = new Intent(context, AlarmReceiver.class);
		setFirstRecentLocation();
		setLastRecentLocation();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		this.db = db;
		db.execSQL("CREATE TABLE " + tableName + " ( " + colId
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," + colName + " TEXT,"
				+ colCategory + " TEXT," + colLatitude + " REAL,"
				+ colLongitude + " REAL," + colAddress + " TEXT,"
				+ colStartTime + " INTEGER," + colEndTime + " INTEGER,"
				+ colState + " TEXT," + colType + " TEXT)");
		db.execSQL("CREATE TABLE " + mustEventsScheduleTable + " ( "
				+ colEventId + " INTEGER PRIMARY KEY," + colEventStartTime
				+ " INTEGER)");
		db.execSQL("CREATE TABLE " + returnLocationTable + " ( " + colId
				+ " INTEGER PRIMARY KEY," + colName + " TEXT," + colLatitude
				+ " REAL," + colLongitude + " REAL," + colAddress + " TEXT)");
		db.execSQL("CREATE TABLE " + recentLocationPoints + " ( " + colId
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," + colLatitude
				+ " REAL," + colLongitude + " REAL)");
		db.execSQL("CREATE TABLE " + userEneteredrecentAddresses + " ( "
				+ colId + " INTEGER PRIMARY KEY AUTOINCREMENT," + colAddress
				+ " TEXT," + colLatitude + " REAL," + colLongitude + " REAL)");
	}

	public boolean saveRecentUserAddress(String addr) throws JSONException {
		db = this.getWritableDatabase();
		boolean result = false;
		ContentValues cv = new ContentValues();
		double geocodes[] = Utilities.getLatAndLng(addr);
		if (Double.compare(geocodes[0], 0.0) != 0
				&& Double.compare(geocodes[1], 0.0) != 0) {
			cv.put(colAddress, addr);
			cv.put(colLatitude, geocodes[0]);
			cv.put(colLongitude, geocodes[1]);
			db.insert(userEneteredrecentAddresses, null, cv);
			result = true;
		} else {
			result = false;
		}
		db.close();
		return result;
	}

	public ContentValues getUserAddressDetails(String addr) {
		db = this.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + userEneteredrecentAddresses
				+ " WHERE " + colAddress + " = ? ", new String[] { addr });
		ContentValues cv = new ContentValues();
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			cv.put(colAddress, addr);
			cv.put(colLatitude, cur.getDouble(2));
			cv.put(colLongitude, cur.getDouble(3));
		}
		cur.close();
		db.close();
		return cv;
	}

	public Cursor getAllUserAddresses(String args) {
		if (db != null) {
			db.close();
		}
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + userEneteredrecentAddresses
				+ " WHERE " + colAddress + " LIKE '%" + args + "%'  ORDER BY "
				+ colAddress, null);
		return cur;
	}

	public void deleteAllUserAddresses() {
		db = this.getWritableDatabase();
		db.delete(userEneteredrecentAddresses, null, null);
		db.close();
	}

	// check if the user entered address is already prsent in the database
	public boolean checkIfPresent(String addr) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + userEneteredrecentAddresses
				+ " WHERE " + colAddress + " = ?", new String[] { addr });
		if (cur.getCount() > 0) {
			cur.close();
			db.close();
			return true;
		}
		cur.close();
		db.close();
		return false;
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		this.db = db;
		db.execSQL("DROP TABLE IF EXISTS " + tableName);
		onCreate(db);
	}

	public void saveEvent(MyEvent e) {
		// write code here to get input from ui and fill the db;
		// User enters only name, category, location(can be auto pick) and
		// time/time interval
		// Need to auto generate id,
		/*
		 * Need to convert location to lat and lon Need to convert Date objects
		 * into Unix time stamps Need to enter a default State of unschedled
		 */
		db = this.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(colName, e.getName());
		cv.put(colCategory, e.getCategory());
		if (e.getLocation() != null) {
			cv.put(colLatitude, e.getLocation().getLatitude());
			cv.put(colLongitude, e.getLocation().getLongitude());
			cv.put(colAddress, e.getLocation().getAddress());
		} else {
			cv.put(colLatitude, 0.0);
			cv.put(colLongitude, 0.0);
			cv.put(colAddress, "autopick");
		}
		cv.put(colStartTime, e.getStartTime().getTime());
		cv.put(colEndTime, e.getEndTime().getTime());
		cv.put(colState, e.getState());
		cv.put(colType, e.getType());
		long id = db.insert(tableName, colAddress, cv);
		if (cv.getAsString(colType).equals("Must")) {
			Long value = cv.getAsLong(colStartTime) - (60 * 60 * 1000);
			ContentValues contents = new ContentValues();
			contents.put(colEventId, id);
			contents.put(colEventStartTime, value); // subtracting 1 hour from
													// the user input start time
													// for the purpose of the
													// notification
			db.insert(mustEventsScheduleTable, null, contents);
			intent.setAction(Intent.ACTION_VIEW);
			intent.setType(Utilities.nextRandomString());
			intent.putExtra("SPECIFIC", "true");
			intent.putExtra("ID", id);
			intent.putExtra("TIME", value);
			requestCode++;
			pendingIntent = PendingIntent.getBroadcast(context, requestCode,
					intent, 0);
			alarmMgr.set(AlarmManager.RTC_WAKEUP, value, pendingIntent);
		}
	}

	public boolean isAutopick(String address) {
		if (address.equals("autopick")) {
			return true;
		} else {
			return false;
		}
	}

	// used as a pointer to maintain a fixed size of most recent user locations
	public void setFirstRecentLocation() {
		db = this.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT MIN(" + colId + ") FROM "
				+ recentLocationPoints, null);
		cur.moveToFirst();
		firstRecentLocation = (cur.getCount() == 1) ? cur.getLong(0) : 1;
		cur.close();
		db.close();
	}

	// used as a pointer to maintain a fixed size of most recent user locations
	public void setLastRecentLocation() {
		db = this.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT MAX(" + colId + ") FROM "
				+ recentLocationPoints, null);
		cur.moveToFirst();
		lastRecentLocation = (cur.getCount() == 1) ? cur.getLong(0) : 1;
		cur.close();
		db.close();
	}

	public void saveRecentLocation(double lat, double lng) {
		db = this.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(colLatitude, lat);
		cv.put(colLongitude, lng);
		if (lastRecentLocation - firstRecentLocation + 1 < size) {
			lastRecentLocation = db.insert(recentLocationPoints, null, cv);
		} else {
			db.delete(recentLocationPoints, "" + colId + "=?"
					+ firstRecentLocation, null);
			firstRecentLocation++;
			lastRecentLocation = db.insert(recentLocationPoints, null, cv);
		}
		db.close();
	}

	public Cursor getAllRecentLocations() {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + recentLocationPoints, null);
		return cur;
	}

	public Cursor getMostRecentLocation() {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + recentLocationPoints
				+ " WHERE " + colId + " = ? ",
				new String[] { String.valueOf(lastRecentLocation) });
		return cur;
	}

	public Cursor getReturnLocation(String name) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + returnLocationTable
				+ " WHERE " + colName + " = ?", new String[] { name });
		return cur;
	}

	public Cursor getAllReturnLocations() {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + returnLocationTable, null);
		return cur;
	}

	public ContentValues saveReturnLocation(String name, String address)
			throws JSONException {
		db = this.getWritableDatabase();
		double geocodes[] = Utilities.getLatAndLng(address);
		ContentValues cv = new ContentValues();
		cv.put(colName, name);
		cv.put(colLatitude, geocodes[0]);
		cv.put(colLongitude, geocodes[1]);
		cv.put(colAddress, address);
		db.insert(returnLocationTable, null, cv);
		return cv;
	}

	public void deleteAllEvents() {
		db = this.getWritableDatabase();
		db.delete(tableName, null, null);
	}

	// Later the list of all EVents should be returned
	public Cursor getAllEvents() {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName, null);
		return cur;
	}

	// Later the argument should be converted to TYPE variable in Event class
	// and return list of Events
	public Cursor getAllEvents(String type) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ?", new String[] { type });
		return cur;
	}

	public ArrayList<MyEvent> getAllEventsList(String type) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ?" + " ORDER BY " + colStartTime + " ASC ",
				new String[] { type });
		ArrayList<MyEvent> listOfEvents = new ArrayList<MyEvent>();
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			int i = 0;
			while (i < cur.getCount()) {
				listOfEvents.add(createEvent(cur.getLong(0), cur.getString(1),
						cur.getString(2), cur.getDouble(3), cur.getDouble(4),
						cur.getString(5), cur.getLong(6), cur.getLong(7),
						cur.getString(8), cur.getString(9)));
				i++;
				cur.moveToNext();
			}
		}
		cur.close();
		db.close();
		return listOfEvents;
	}

	// used for creating an Event object based on the details provided by the
	// database table
	public MyEvent createEvent(long id, String name, String category,
			Double lat, Double lng, String address, Long startTime,
			Long endTime, String state, String type) {

		MyLocation myloc;
		if (isAutopick(address)) {
			myloc = null;
		} else {
			myloc = createLocation(lat, lng, address);
		}
		Date startDate = Utilities.convertMillistoDate(startTime);
		Date endDate = Utilities.convertMillistoDate(endTime);
		return new MyEvent(id, name, category, myloc, startDate, endDate,
				state, type);
	}

	public MyLocation createLocation(Double lat, Double lng, String address) {
		return new MyLocation(lat, lng, address);
	}

	// Later the argument should be converted to Date Type format. Date should
	// be converted in turn into Integers/UTC
	public Cursor getAllMustToDoEventsBetween(Long start, Long end) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ? " + "AND " + colState + " = ? " + " AND "
				+ colStartTime + " >= " + start + " AND " + colEndTime + " <= "
				+ end, new String[] { "Must", "unscheduled" });
		return cur;
	}

	public ArrayList<MyEvent> getAllMustToDoEventsListBetween(Long start,
			Long end) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ?" + "AND " + colState + " = ? " + " AND "
				+ colStartTime + " >= " + start + " AND " + colEndTime + " <= "
				+ end + " ORDER BY " + colStartTime + " ASC ", new String[] {
				"Must", "unscheduled" });
		ArrayList<MyEvent> listOfEvents = new ArrayList<MyEvent>();
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			int i = 0;
			while (i < cur.getCount()) {
				listOfEvents.add(createEvent(cur.getLong(0), cur.getString(1),
						cur.getString(2), cur.getDouble(3), cur.getDouble(4),
						cur.getString(5), cur.getLong(6), cur.getLong(7),
						cur.getString(8), cur.getString(9)));
				cur.moveToNext();
				i++;
			}
		}
		cur.close();
		db.close();
		return listOfEvents;
	}

	// Later the argument should be converted to Date Type format. Date should
	// be converted in turn into Integers/UTC
	public Cursor getAllGoodToDoEventsBetween(Long start, Long end) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ? " + "AND " + colState + " = ? " + " AND "
				+ "(" + colStartTime + " >= " + start + " OR " + colEndTime
				+ " <= " + end + ")", new String[] { "Good", "unscheduled" });
		return cur;
	}

	public ArrayList<MyEvent> getAllGoodToDoEventsListBetween(Long start,
			Long end) {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ?" + "AND " + colState + " = ? " + " AND "
				+ "(" + colStartTime + " >= " + start + " OR " + colEndTime
				+ " <= " + end + ")" + " ORDER BY " + colStartTime + " ASC ",
				new String[] { "Good", "unscheduled" });
		ArrayList<MyEvent> listOfEvents = new ArrayList<MyEvent>();
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			int i = 0;
			while (i < cur.getCount()) {
				listOfEvents.add(createEvent(cur.getLong(0), cur.getString(1),
						cur.getString(2), cur.getDouble(3), cur.getDouble(4),
						cur.getString(5), cur.getLong(6), cur.getLong(7),
						cur.getString(8), cur.getString(9)));
				cur.moveToNext();
				i++;
			}
		}
		cur.close();
		db.close();
		return listOfEvents;
	}

	// Later the argument should be converted to Date Type format. Date should
	// be converted in turn into Integers/UTC
	public Cursor getAllGoodToDoEventsNotInBetween(long start, long end) {
		db = this.getReadableDatabase();
		long today = Utilities.getCurrentTime();
		// get current day. no need of time. to avoid
		// cycling back to previous events. May need to
		// exclude this. Think!
		Cursor cur = db.rawQuery(
				"SELECT * FROM " + tableName + " WHERE " + colType + " = ? "
						+ "AND " + colState + " = ? " + " AND " + "("
						+ colStartTime + " <= " + start + " AND " + colEndTime
						+ " >= " + end + " AND " + colStartTime + " >= "
						+ today + " )", new String[] { "Good", "unscheduled" });
		return cur;
	}

	public ArrayList<MyEvent> getAllGoodToDoEventsListNotInBetween(Long start,
			Long end) {
		db = this.getReadableDatabase();
		long today = Utilities.getCurrentTime();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ? " + "AND " + colState + " = ? " + " AND "
				+ "(" + colStartTime + " <= " + start + " AND " + colEndTime
				+ " >= " + end + " AND " + colStartTime + " >= " + today + " )"
				+ " ORDER BY " + colStartTime + " ASC ", new String[] { "Good",
				"unscheduled" });
		ArrayList<MyEvent> listOfEvents = new ArrayList<MyEvent>();
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			int i = 0;
			while (i < cur.getCount()) {
				listOfEvents.add(createEvent(cur.getLong(0), cur.getString(1),
						cur.getString(2), cur.getDouble(3), cur.getDouble(4),
						cur.getString(5), cur.getLong(6), cur.getLong(7),
						cur.getString(8), cur.getString(9)));
				cur.moveToNext();
				i++;
			}
		}
		cur.close();
		db.close();
		return listOfEvents;
	}

	// Later the argument should be converted to Date Type format. Date should
	// be converted in turn into Integers/UTC
	public Cursor getAllUnscheduledGoodToDoEvents() {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ? " + "AND " + colState + " = ? ",
				new String[] { "Good", "unscheduled" });
		return cur;
	}

	public ArrayList<MyEvent> getAllUnscheduledGoodToDoEventsList() {
		db = this.getReadableDatabase();

		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colType + " = ? " + "AND " + colState + " = ? "
				+ " ORDER BY " + colStartTime + " ASC ", new String[] { "Good",
				"unscheduled" });

		ArrayList<MyEvent> listOfEvents = new ArrayList<MyEvent>();
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			int i = 0;
			while (i < cur.getCount()) {
				listOfEvents.add(createEvent(cur.getLong(0), cur.getString(1),
						cur.getString(2), cur.getDouble(3), cur.getDouble(4),
						cur.getString(5), cur.getLong(6), cur.getLong(7),
						cur.getString(8), cur.getString(9)));
				cur.moveToNext();
				i++;
			}
		}
		cur.close();
		db.close();
		return listOfEvents;
	}

	public Cursor getMustEventSchedule(long id) {
		db = this.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + mustEventsScheduleTable
				+ " WHERE " + colEventId + " = ? ", new String[] { "" + id });
		return cur;
	}

	public Cursor getAllCompletedEvents() {
		db = this.getReadableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colState + " = ?", new String[] { "completed" });
		return cur;
	}

	public ArrayList<MyEvent> getAllInProgressEvents(long start, long end) {
		db = this.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colState + " = ?", new String[] { "inprogress" });
		ArrayList<MyEvent> listOfEvents = new ArrayList<MyEvent>();
		ArrayList<Long> forStateUpdation = new ArrayList<Long>();
		if (cur != null && cur.getCount() > 0) {
			cur.moveToFirst();
			int i = 0;
			while (i < cur.getCount()) {
				if ((cur.getLong(6) >= start) || (cur.getLong(7) <= end)) {
					listOfEvents.add(createEvent(cur.getLong(0),
							cur.getString(1), cur.getString(2),
							cur.getDouble(3), cur.getDouble(4),
							cur.getString(5), cur.getLong(6), cur.getLong(7),
							cur.getString(8), cur.getString(9)));
				} else {
					forStateUpdation.add(cur.getLong(0));
				}
				cur.moveToNext();
				i++;
			}
		}
		if (cur != null)
			cur.close();
		db.close();
		for (int i = 0; i < forStateUpdation.size(); i++) {
			updateEventStatus(forStateUpdation.get(i), "unscheduled");
		}
		return listOfEvents;
	}

	public Cursor getEventsDueToday() {
		db = this.getReadableDatabase();
		long today = Utilities.getTodaysTimeStamp();
		long tmrw = Utilities.getTomorrowsTimeStamp();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colEndTime + " > " + today + " AND " + colEndTime + " < "
				+ tmrw + " AND " + colState + " = ?",
				new String[] { "unscheduled" });
		// write code here to get all events whose state is unscheduled and
		// whose EndTime is today.
		return cur;
	}

	public Cursor getEventsDueTomorrow() {
		db = this.getReadableDatabase();
		long tmrw = Utilities.getTomorrowsTimeStamp();
		long dayAfterTmrw = Utilities.getDayAfterTomorrowsTimeStamp();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colEndTime + " > " + tmrw + " AND " + colEndTime + " < "
				+ dayAfterTmrw + " AND " + colState + "=?",
				new String[] { "unscheduled" });
		// write code here to get all events whose state is unscheduled and
		// whose EndTime is today.
		return cur;
	}

	public Cursor getEventsDueThisWeek() {
		db = this.getReadableDatabase();
		long currentWeek = Utilities.getCurrentWeeksTimeStamp();
		long nextWeek = Utilities.getNextWeeksTimeStamp();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colState + " = ?" + " AND " + colEndTime + " > "
				+ currentWeek + " AND " + colEndTime + " < " + nextWeek,
				new String[] { "unscheduled" });
		// write code here to get all events whose state is unscheduled and
		// whose EndTime is today.
		return cur;
	}

	public Cursor getEventsDueNextWeek() {
		db = this.getReadableDatabase();
		long nextWeek = Utilities.getNextWeeksTimeStamp();
		long nextNextWeek = Utilities.getNextNextWeeksTimeStamp();
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colState + " = ?" + " AND " + colEndTime + " > " + nextWeek
				+ " AND " + colEndTime + " < " + nextNextWeek,
				new String[] { "unscheduled" });
		// write code here to get all events whose state is unscheduled and
		// whose EndTime is today.
		return cur;
	}

	public Cursor getOverdueEvents() {
		db = this.getReadableDatabase();
		long now = (Calendar.getInstance().getTimeInMillis());
		Cursor cur = db.rawQuery("SELECT * FROM " + tableName + " WHERE "
				+ colState + " = ?" + " AND " + colEndTime + " < " + now,
				new String[] { "unscheduled" });
		return cur;
	}

	public void deleteEventSchedule(long id) {
		db = this.getWritableDatabase();
		db.delete(mustEventsScheduleTable, "" + colEventId + "=?" + id, null);
		db.close();
	}

	public void updateEventStatus(long id, String status) {
		db = this.getWritableDatabase();
		String strFilter = "_id=" + id;
		ContentValues values = new ContentValues();
		values.put(colState, status);
		int resId = db.update(tableName, values, strFilter, null);
		db.close();
	}
	
	public int updateAllInProgressEventsStatus(){
		db = this.getWritableDatabase();
		String strFilter = colState + "=\'inprogress\'";
		ContentValues values = new ContentValues();
		values.put(colState, "unscheduled");
		int resId = db.update(tableName, values, strFilter, null);
		db.close();
		return resId;
	}

	public void updateEvent() {
		/*
		 * TODO later based on the event object that will be passed as Argument
		 * take the event id, delete and then insert with new value and same
		 * event id. int id = event.getId(); //event Id can never be updated by
		 * user
		 */
		db = this.getWritableDatabase();
		// db.update();
		/*
		 * TODO update the hashmap/table consisting even schedules!
		 * if(cv.getAsString(colType).equals("Must")){ Integer key =
		 * cv.getAsInteger(colId); Long value = cv.getAsLong(colStartTime);
		 * mustEventsSchedule.put(key, value);
		 * intent.setAction(Intent.ACTION_VIEW);
		 * intent.setType(Utilities.nextRandomString());
		 * intent.putExtra("SPECIFIC", "true"); intent.putExtra("ID", key);
		 * intent.putExtra("TIME", value); requestCode++; pendingIntent =
		 * PendingIntent.getBroadcast(context, requestCode, intent, 0); long
		 * time = cv.getAsLong(colStartTime) * 1000;
		 * alarmMgr.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); }
		 */
		/*
		 * TODO Trigger alarm here
		 */
	}

	// Should later chagne the aRgument to an Event object
	public void deleteEvent(long id) {
		db = this.getWritableDatabase();
		db.delete(tableName, "" + colId + "=" + id, null);
		db.close();
		Cursor cur = getMustEventSchedule(id);
		if (cur != null) {
			db.close();
			deleteEventSchedule(id);
		}
		/*
		 * if(mustEventsSchedule.containsKey(id)){
		 * mustEventsSchedule.remove(id); }
		 */
	}

	// Should later chagne the aRgument to an Event object
	public void deleteCompletedEvents() {
		db = this.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT " + colId + " FROM " + tableName
				+ " WHERE " + colState + " = ? ", new String[] { "completed" });
		int count = cur.getCount();
		cur.moveToFirst();
		for (int i = 0; i < count & cur != null; i++) {
			deleteEvent(Long.parseLong(String.valueOf(cur.getInt(0))));
			cur.moveToNext();
		}
		cur.close();
		db.close();
	}
}
